<template>
  <div class="note-editor">
    <template v-if="activeNote">
      <div class="editor-header">
        <el-input
          v-model="title"
          placeholder="笔记标题"
          class="title-input"
          @change="updateTitle"
        />
        <div class="editor-toolbar">
          <template v-if="activeNote.type === 'markdown'">
            <el-button-group>
              <el-button :icon="Edit" :type="isPreview ? '' : 'primary'" @click="togglePreview">编辑</el-button>
              <el-button :icon="View" :type="isPreview ? 'primary' : ''" @click="togglePreview">预览</el-button>
            </el-button-group>
          </template>
          <el-button-group>
            <el-button :icon="Download" @click="exportNote">导出</el-button>
            <el-button :icon="Lock" v-if="!activeNote.encrypted" @click="encryptNote">加密</el-button>
            <el-button :icon="Unlock" v-else @click="decryptNote">解密</el-button>
            <el-button :icon="Timer" @click="showHistory">历史</el-button>
          </el-button-group>
        </div>
      </div>

      <div class="editor-content">
        <markdown-editor
          v-if="activeNote.type === 'markdown'"
          v-model="content"
          :preview-mode="isPreview"
          @save="saveNote"
          @update:modelValue="handleContentChange"
        />
        <rich-text-editor
          v-else
          v-model="content"
          @save="saveNote"
          @update:modelValue="handleContentChange"
        />
      </div>
    </template>

    <div v-else class="no-note">
      <note-empty />
    </div>

    <!-- 历史记录查看器 -->
    <history-viewer
      v-if="activeNote"
      v-model="showHistoryViewer"
      :note-id="activeNote.id"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
import { storeToRefs } from 'pinia'
import { Edit, View, Download, Lock, Unlock, Timer } from '@element-plus/icons-vue'
import { useEditorStore } from '@/stores/editor'
import { useSettingsStore } from '@/stores/settings'
import HistoryViewer from './HistoryViewer.vue'
import MarkdownEditor from './MarkdownEditor.vue'
import RichTextEditor from './RichTextEditor.vue'
import { ElMessage } from 'element-plus'
import NoteEmpty from "@/components/editor/NoteEmpty.vue";

const editorStore = useEditorStore()
const settingsStore = useSettingsStore()

const { activeNote } = storeToRefs(editorStore)
const title = ref('')
const content = ref('')
const isPreview = ref(false)
const showHistoryViewer = ref(false)

// 监听活动笔记变化
watch(activeNote, (note) => {
  if (note) {
    title.value = note.title
    content.value = note.content
  } else {
    title.value = ''
    content.value = ''
  }
}, { immediate: true })

// 更新标题
const updateTitle = () => {
  if (activeNote.value) {
    editorStore.updateNoteTitle(activeNote.value.id, title.value)
  }
}

// 更新内容
const handleContentChange = (newContent: string) => {
  if (activeNote.value) {
    editorStore.updateNote(activeNote.value.id, newContent)
  }
}

// 保存笔记
const saveNote = async () => {
  if (activeNote.value) {
    try {
      await editorStore.saveNote(activeNote.value.id)
    } catch (error) {
      console.error('Failed to save note:', error)
      ElMessage.error('保存笔记失败')
    }
  }
}

// 切换预览
const togglePreview = () => {
  isPreview.value = !isPreview.value
}

// 显示历史记录
const showHistory = () => {
  showHistoryViewer.value = true
}

const exportNote = () => {
  // TODO: 实现笔记导出功能
}

const encryptNote = () => {
  // TODO: 实现笔记加密功能
}

const decryptNote = () => {
  // TODO: 实现笔记解密功能
}

// 快捷键处理
const handleKeyDown = (e: KeyboardEvent) => {
  // Ctrl/Cmd + S: 保存
  if ((e.ctrlKey || e.metaKey) && e.key === 's') {
    e.preventDefault()
    saveNote()
  }
}

// 注册快捷键
onMounted(() => {
  window.addEventListener('keydown', handleKeyDown)
})

onUnmounted(() => {
  window.removeEventListener('keydown', handleKeyDown)
})
</script>

<style lang="scss" scoped>
.note-editor {
  flex: 1;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background: var(--el-bg-color);

  .editor-header {
    flex-shrink: 0;
    padding: 16px;
    border-bottom: 1px solid var(--el-border-color-light);
    display: flex;
    align-items: center;
    gap: 16px;

    .title-input {
      flex: 1;
      max-width: 300px;

      :deep(.el-input__inner) {
        font-size: 18px;
        font-weight: bold;
      }
    }

    .editor-toolbar {
      display: flex;
      gap: 8px;
    }
  }

  .editor-content {
    flex: 1;
    width: 100%;
    min-height: 0;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    :deep(.markdown-editor),
    :deep(.richtext-editor) {
      flex: 1;
      width: 100%;
      height: 100%;
      display: flex;
      flex-direction: column;
    }
  }

  .no-note {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
